import { CallHandler, ExecutionContext, Injectable, NestInterceptor, HttpStatus } from '@nestjs/common';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { Request, Response } from 'express';
@Injectable()
export class CommonInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    // const request = context.switchToHttp().getRequest();
    const request = context.switchToHttp().getRequest<Request>();
    const response = context.switchToHttp().getResponse<Response>();
    //post返回 200
    if(request.method === 'POST' && response.statusCode === HttpStatus.CREATED) response.status(HttpStatus.OK)
    return next.handle().pipe(
      map((data) => {
        let result = {}
        switch(typeof data){
          case "string":
          case "boolean":
            result = { data }
            break;
          case "object":
            result = data
            break;
        }
        return {
          code: 200,
          timestamp: new Date().toLocaleString(),
          path: request.url,
          message: '请求成功',
          ...result
        };
      }),
    );
  }
}
